package com.android.example.record.activity;

import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import com.android.example.record.R;
import com.android.example.record.adapter.HistoryDataAdapter;
import com.android.example.record.bean.HistoryData;
import com.android.example.record.databinding.ActivityQueryDataBinding;
import com.android.example.record.utils.PopupDataUtil;
import com.android.example.record.utils.Utils;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class QueryDataActivity extends AppCompatActivity {

    private ActivityQueryDataBinding binding;
    private String year;
    private String month;
    private String day;
    private String date;
    private String number;
    private String siren;

    private final List<HistoryData> subHistoryDataList = new ArrayList<>();
    private HistoryDataAdapter historyDataAdapter;

    Toast toast;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityQueryDataBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);

        initData(" ", " ", " ");
        initView();
        historyDataAdapter.setOnItemClickListener(ItemClickListener);

        binding.queryButton.setOnClickListener(this::queryData);
    }

    private void queryData(View view) {
        year = String.format("%4s", binding.yearText.getText().toString()).replaceAll("\\s", "0");
        month = String.format("%2s", binding.monthText.getText().toString()).replaceAll("\\s", "0");
        day = String.format("%2s", binding.dayText.getText().toString()).replaceAll("\\s", "0");
        number = binding.numberText.getText().toString().trim();
        siren = binding.sirenText.getText().toString().trim();

        if (!year.equals("0000")) {
            date = year;
            if (!month.equals("00")) {
                date += "-" + month;
                if (!day.equals("00")) {
                    date += "-" + day;
                }
            }
        } else {
            date = "";
        }

        if (toast != null) {
            toast.cancel();
        }
        refreshData(date, number, siren);
        if (subHistoryDataList.size() == 0) {
            toast = Toast.makeText(this, "查询无结果", Toast.LENGTH_SHORT);
        } else {
            toast = Toast.makeText(this, "查询成功", Toast.LENGTH_SHORT);
        }
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    private void refreshData(String date, String number, String siren) {
        runOnUiThread(() -> {
            historyDataAdapter.notifyItemRangeRemoved(0, subHistoryDataList.size());
            binding.subRecyclerView.removeAllViews();
            subHistoryDataList.clear();
            initData(date, number, siren);
            historyDataAdapter.notifyItemRangeInserted(0, subHistoryDataList.size());
            Utils.closeKeyboard(this);
        });
    }

    public List<HistoryData> getHistoryDataList(String date, String number, String siren) {
        List<HistoryData> mHistoryDataList = Collections.emptyList();
        if (TextUtils.isEmpty(date) && TextUtils.isEmpty(number) && TextUtils.isEmpty(siren)) {
            return mHistoryDataList;
        }

        if (TextUtils.isEmpty(number) && TextUtils.isEmpty(siren)) {
            mHistoryDataList = LitePal.select("*")
                    .where("INSTR (save_date, ?) = 1", date).find(HistoryData.class);

            return mHistoryDataList;
        }
        if (TextUtils.isEmpty(date) && TextUtils.isEmpty(siren)) {
            mHistoryDataList = LitePal.select("*")
                    .where("number = ?", number).find(HistoryData.class);
            return mHistoryDataList;
        }
        if (TextUtils.isEmpty(date) && TextUtils.isEmpty(number)) {
            mHistoryDataList = LitePal.select("*")
                    .where("siren = ?", siren).find(HistoryData.class);
            return mHistoryDataList;
        }

        if (TextUtils.isEmpty(siren)) {
            mHistoryDataList = LitePal.select("*")
                    .where("INSTR (save_date, ?) = 1 and number = ?", date, number).find(HistoryData.class);
            return mHistoryDataList;
        }

        if (TextUtils.isEmpty(number)) {
            mHistoryDataList = LitePal.select("*")
                    .where("INSTR (save_date, ?) = 1 and siren = ?", date, siren).find(HistoryData.class);
            return mHistoryDataList;
        }

        if (TextUtils.isEmpty(date)) {
            mHistoryDataList = LitePal.select("*")
                    .where("number = ? and siren = ?", number, siren).find(HistoryData.class);
            return mHistoryDataList;
        }

        mHistoryDataList = LitePal.select("*")
                .where("INSTR (save_date, ?) = 1 and number = ? and siren = ?", date, number, siren).find(HistoryData.class);

        return mHistoryDataList;
    }

    /**
     * List<HistoryDataList>、HistoryDataAdapter初始化。
     *
     * @param date   日期
     * @param number 车牌号
     * @param siren  警号
     */
    private void initData(String date, String number, String siren) {
        subHistoryDataList.addAll(getHistoryDataList(date, number, siren));
        historyDataAdapter = new HistoryDataAdapter(subHistoryDataList);
    }

    private final HistoryDataAdapter.OnItemClickListener ItemClickListener = new HistoryDataAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View view, HistoryDataAdapter.ViewName viewName, int position) {
            if (view.getId() == R.id.options) {
                PopupDataUtil.showPopupWindow(position, QueryDataActivity.this, subHistoryDataList);
            }
        }

        @Override
        public void onItemLongClick(View view) {

        }
    };

    private void initView() {
        setSupportActionBar(binding.toolbar);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        binding.yearText.setRawInputType(InputType.TYPE_CLASS_NUMBER);
        binding.monthText.setRawInputType(InputType.TYPE_CLASS_NUMBER);
        binding.dayText.setRawInputType(InputType.TYPE_CLASS_NUMBER);
        binding.sirenText.setRawInputType(InputType.TYPE_CLASS_NUMBER);

        GridLayoutManager layoutManager = new GridLayoutManager(this, 1);
        binding.subRecyclerView.setLayoutManager(layoutManager);
        binding.subRecyclerView.setAdapter(historyDataAdapter);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            return true;
        }

        return true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        finish();
    }
}